package com.bq.gametrade.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.GamesList;
import com.bq.gametrade.bean.GamesListDetails;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.utils.CheckUtils;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.view.CustomSpinner;
import com.bq.gametrade.view.TimeButton;
import com.bq.gametrade.view.popwindow.SelectGameNamesPop;
import com.bq.gametrade.widget.PromptAlertDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BindingGamesAccountActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back;
    private TextView tvTitle;
    private CustomSpinner spGamseList;
    private EditText etGamesAccount, etAccountPassword, etPhoneNumber, etVerificationCode;
    private Button btnComit;
    private TextView getCode;
    private TextView tvGamesNameSelect;

    private List<GamesListDetails> list = new ArrayList<>();
    private String gamesId;
    private String gamesName;
    private UserInfoDetails userInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binding_gamesaccount);
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        getGameList();
        initView();

    }

    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("绑定账号");
        etGamesAccount = serchViewById(R.id.et_gamesAccount);
        etAccountPassword = serchViewById(R.id.et_AccountPassword);
        etPhoneNumber = serchViewById(R.id.et_phoneNumber);
        etVerificationCode = serchViewById(R.id.et_verificationCode);
        btnComit = serchViewById(R.id.btn_commit);
        btnComit.setOnClickListener(this);
        getCode = serchViewById(R.id.get_code);
        getCode.setOnClickListener(this);
        etPhoneNumber.setText(application.getUserInfo().account);
        etPhoneNumber.setEnabled(false);
        tvGamesNameSelect = serchViewById(R.id.tv_gamesNameSelect);
        tvGamesNameSelect.setOnClickListener(this);


    }

    private void initSpinner(final List<GamesListDetails> lists) {
        spGamseList = serchViewById(R.id.sp_gamesList);

        spGamseList.init(this, lists);
        spGamseList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spGamseList.showWindow();
            }
        });

        spGamseList.setOnSpinnerItemClickListener(new CustomSpinner.OnSpinnerItemClickListener() {
            @Override
            public void OnSpinnerItemClick(AdapterView<?> parent, View view, int position, long id) {
                gamesId = lists.get(position).id;
                gamesName = lists.get(position).serverName;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_gamesNameSelect:
                SelectGameNamesPop pop= new SelectGameNamesPop(BindingGamesAccountActivity.this,list,tvGamesNameSelect.getText().toString());
                pop.showAsDropDown(tvGamesNameSelect);
                pop.setOnGetNameListener(new SelectGameNamesPop.OnGetNameListener() {
                    @Override
                    public void getName(int position) {
                        tvGamesNameSelect.setText(list.get(position).serverName);
                    }
                });
                break;
            case R.id.image_back:
                finish();
                break;
            case R.id.get_code:
                if (TextUtils.isEmpty(etGamesAccount.getText().toString())) {
                    toastShow("游戏账号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etAccountPassword.getText().toString())) {
                    toastShow("游戏密码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etPhoneNumber.getText().toString())) {
                    toastShow("手机号码不能为空");
                    return;
                }
                if (!CheckUtils.isMobile(etPhoneNumber.getText().toString())) {
                    toastShow("手机号码不正确");
                    return;
                }
                if (!NetworkUtils.isNetworkAvailable(BindingGamesAccountActivity.this)) {
                    toastShow("网络异常，请检查你的网络");
                    return;
                }
                sendCode();
                break;
            case R.id.btn_commit:
                if (!NetworkUtils.isNetworkAvailable(BindingGamesAccountActivity.this)) {
                    toastShow("网络异常，请检查你的网络");
                    return;
                }
                new PromptAlertDialog(BindingGamesAccountActivity.this).builder().setTitle("提示").setTouchOutsideCanceled(true)
                        .setMsg("您正在绑定《" + gamesName + "》的账号")
                        .setPositiveButton("绑定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                toBindGames();
                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();
                break;

        }
    }


    private void sendCode() {
        /**
         * 注册时验证码类型：codeType = 0;
         */
        String codeType = "1";
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("tel", etPhoneNumber.getText().toString());
        params.put("codeType", codeType);
        showSpotsDialog("正在发送验证码···");
        VRHttp.sendRequest(BindingGamesAccountActivity.this, HttpLink.GET_VERIFICATIONCODE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("已发送！请查看");
                        TimeButton timeButton = new TimeButton(BindingGamesAccountActivity.this, 60 * 1000, 1000, getCode);
                        timeButton.start();
                    } else if (bean.status.equals("1")) {
                        toastShow("获取验证码失败！");
                    }
                } else {
                    toastShow("获取验证码失败");
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("发送验证码失败");
                closeSpotsDialog();
            }
        });
    }


    private void getGameList() {
        Map<String, String> params = new HashMap<>();
        showSpotsDialog();
        VRHttp.getGamesNameList(BindingGamesAccountActivity.this, HttpLink.GAMES_LIST_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if (response != null) {
                    GamesList gameList = (GamesList) response;
                    if (gameList.status.equals("0")) {
                        list = gameList.gamesList;
                        if (list.size() > 0) {
                            gamesId = list.get(0).id;
                            gamesName = list.get(0).serverName;
                            tvGamesNameSelect.setText(gamesName);
                        }
                        initSpinner(list);
                    } else {
                        toastShow("获取游戏列表失败");
                    }

                }

            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("获取游戏列表失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();

            }
        });

    }

    private void toBindGames() {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("gameId", gamesId);
        params.put("account", application.getUserInfo().telNum);
        params.put("pwd", "0");
        showSpotsDialog("正在绑定····");
        VRHttp.sendRequest(BindingGamesAccountActivity.this, HttpLink.BIND_GAMESACCOUNT_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("绑定成功");
                        finish();
                    } else if (bean.status.equals("99")) {
                        toastShow("登录超时，请重新登陆");
                        application.setUserInfo(null);
                        startActivity(new Intent(BindingGamesAccountActivity.this, LoginActivity.class));
                        finish();
                    } else if (bean.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(BindingGamesAccountActivity.this, LoginActivity.class));
                        finish();
                    }else {
                        toastShow("绑定失败！请重试");
                    }
                } else {
                    toastShow("绑定失败！请重试");
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                closeSpotsDialog();
                toastShow("绑定失败请重试");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }
}
